﻿// Global.asax.cs
//

using System;
using System.ServiceModel.DomainServices.Server;
using System.ServiceModel.DomainServices.Server.ApplicationServices;
using System.Web;
using BookClub.Web.DataModel;
using BookClub.Web.Services;
using BookClub.Web.WebServices.Amazon;
using BookClub.Web.WebServices.Notification;

namespace BookClub.Web {

    public class Global : WebContext {

        protected void Application_Start(object sender, EventArgs e) {
            DomainServiceFactory.Setup();
        }


        internal sealed class DomainServiceFactory : IDomainServiceFactory {

            private IDomainServiceFactory _defaultFactory;

            public DomainServiceFactory(IDomainServiceFactory defaultFactory) {
                _defaultFactory = defaultFactory;
            }

            public DomainService CreateDomainService(Type domainServiceType, DomainServiceContext context) {
                if ((domainServiceType == typeof(BookShelfService)) ||
                    (domainServiceType == typeof(BookClubService))) {
                    User currentUser = Authentication.GetUser<User, AuthenticationService>(context);

                    DomainService domainService =
                        (DomainService)Activator.CreateInstance(domainServiceType,
                                                                currentUser, new AmazonService(), new MailService());
                    domainService.Initialize(context);

                    return domainService;
                }

                return _defaultFactory.CreateDomainService(domainServiceType, context);
            }

            public void ReleaseDomainService(DomainService domainService) {
                if ((domainService is BookShelfService) ||
                    (domainService is BookClubService)) {
                    domainService.Dispose();
                }
                else {
                    _defaultFactory.ReleaseDomainService(domainService);
                }
            }

            public static void Setup() {
                if (!(DomainService.Factory is DomainServiceFactory)) {
                    DomainService.Factory = new DomainServiceFactory(DomainService.Factory);
                }
            }
        }
    }
}
